Fixed some obvious bugs with the new code and implemented If-Modified-Since handling
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 * @package MediaWiki
4 */
5
6 /**
7 * Class to represent an image
8 *
9 * Provides methods to retrieve paths (physical, logical, URL),
10 * to generate thumbnails or for uploading.
11 * @package MediaWiki
12 */
13 class Image
14 {
15 /**#@+
16 * @access private
17 */
18 var $name, # name of the image (constructor)
19 $imagePath, # Path of the image (loadFromXxx)
20 $url, # Image URL (accessor)
21 $title, # Title object for this image (constructor)
22 $fileExists, # does the image file exist on disk? (loadFromXxx)
23 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
24 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
25 $historyRes, # result of the query for the image's history (nextHistoryLine)
26 $width, # \
27 $height, # |
28 $bits, # --- returned by getimagesize (loadFromXxx)
29 $type, # |
30 $attr, # /
31 $size, # Size in bytes (loadFromXxx)
32 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
33
34
35 /**#@-*/
36
37 /**
38 * Create an Image object from an image name
39 *
40 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
41 * @access public
42 */
43 function newFromName( $name ) {
44 $title = Title::makeTitleSafe( NS_IMAGE, $name );
45 return new Image( $title );
46 }
47
48 /**
49 * Obsolete factory function, use constructor
50 */
51 function newFromTitle( $title ) {
52 return new Image( $title );
53 }
54
55 function Image( $title ) {
56 $this->title =& $title;
57 $this->name = $title->getDBkey();
58
59 $n = strrpos( $this->name, '.' );
60 $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
61 $this->historyLine = 0;
62
63 $this->dataLoaded = false;
64 }
65
66 /**
67 * Get the memcached keys
68 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
69 */
70 function getCacheKeys( $shared = false ) {
71 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
72
73 $foundCached = false;
74 $hashedName = md5($this->name);
75 $keys = array( "$wgDBname:Image:$hashedName" );
76 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
77 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
78 }
79 return $keys;
80 }
81
82 /**
83 * Try to load image metadata from memcached. Returns true on success.
84 */
85 function loadFromCache() {
86 global $wgUseSharedUploads, $wgMemc;
87 $fname = 'Image::loadFromMemcached';
88 wfProfileIn( $fname );
89 $this->dataLoaded = false;
90 $keys = $this->getCacheKeys();
91 $cachedValues = $wgMemc->get( $keys[0] );
92
93 // Check if the key existed and belongs to this version of MediaWiki
94 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
95 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
96 # if this is shared file, we need to check if image
97 # in shared repository has not changed
98 if ( isset( $keys[1] ) ) {
99 $commonsCachedValues = $wgMemc->get( $keys[1] );
100 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
101 $this->name = $commonsCachedValues['name'];
102 $this->imagePath = $commonsCachedValues['imagePath'];
103 $this->fileExists = $commonsCachedValues['fileExists'];
104 $this->width = $commonsCachedValues['width'];
105 $this->height = $commonsCachedValues['height'];
106 $this->bits = $commonsCachedValues['bits'];
107 $this->type = $commonsCachedValues['type'];
108 $this->size = $commonsCachedValues['size'];
109 $this->fromSharedDirectory = true;
110 $this->dataLoaded = true;
111 }
112 }
113 }
114 else {
115 $this->name = $cachedValues['name'];
116 $this->imagePath = $cachedValues['imagePath'];
117 $this->fileExists = $cachedValues['fileExists'];
118 $this->width = $cachedValues['width'];
119 $this->height = $cachedValues['height'];
120 $this->bits = $cachedValues['bits'];
121 $this->type = $cachedValues['type'];
122 $this->size = $cachedValues['size'];
123 $this->fromSharedDirectory = false;
124 $this->dataLoaded = true;
125 }
126 }
127
128 wfProfileOut( $fname );
129 return $this->dataLoaded;
130 }
131
132 /**
133 * Save the image metadata to memcached
134 */
135 function saveToCache() {
136 global $wgMemc;
137 $this->load();
138 // We can't cache metadata for non-existent files, because if the file later appears
139 // in commons, the local keys won't be purged.
140 if ( $this->fileExists ) {
141 $keys = $this->getCacheKeys();
142
143 $cachedValues = array('name' => $this->name,
144 'imagePath' => $this->imagePath,
145 'fileExists' => $this->fileExists,
146 'fromShared' => $this->fromSharedDirectory,
147 'width' => $this->width,
148 'height' => $this->height,
149 'bits' => $this->bits,
150 'type' => $this->type,
151 'size' => $this->size);
152
153 $wgMemc->set( $keys[0], $cachedValues );
154 }
155 }
156
157 /**
158 * Load metadata from the file itself
159 */
160 function loadFromFile() {
161 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
162 $fname = 'Image::loadFromFile';
163 wfProfileIn( $fname );
164 $this->imagePath = $this->getFullPath();
165 $this->fileExists = file_exists( $this->imagePath );
166 $gis = false;
167
168 # If the file is not found, and a shared upload directory is used, look for it there.
169 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
170 # In case we're on a wgCapitalLinks=false wiki, we
171 # capitalize the first letter of the filename before
172 # looking it up in the shared repository.
173 $sharedImage = Image::newFromName( $wgLang->ucfirst($this->name) );
174 $this->fileExists = file_exists( $sharedImage->getFullPath(true) );
175 if ( $this->fileExists ) {
176 $this->name = $sharedImage->name;
177 $this->imagePath = $this->getFulPath(true);
178 $this->fromSharedDirectory = true;
179 }
180 }
181
182 if ( $this->fileExists ) {
183 # Get size in bytes
184 $s = stat( $this->imagePath );
185 $this->size = $s['size'];
186
187 # Height and width
188 # Don't try to get the width and height of sound and video files, that's bad for performance
189 if ( !Image::isKnownImageExtension( $this->extension ) ) {
190 $gis = false;
191 } elseif( $this->extension == 'svg' ) {
192 wfSuppressWarnings();
193 $gis = wfGetSVGsize( $this->imagePath );
194 wfRestoreWarnings();
195 } else {
196 wfSuppressWarnings();
197 $gis = getimagesize( $this->imagePath );
198 wfRestoreWarnings();
199 }
200 }
201 if( $gis === false ) {
202 $this->width = 0;
203 $this->height = 0;
204 $this->bits = 0;
205 $this->type = 0;
206 } else {
207 $this->width = $gis[0];
208 $this->height = $gis[1];
209 $this->type = $gis[2];
210 if ( isset( $gis['bits'] ) ) {
211 $this->bits = $gis['bits'];
212 } else {
213 $this->bits = 0;
214 }
215 }
216 $this->dataLoaded = true;
217 wfProfileOut( $fname );
218 }
219
220 /**
221 * Load image metadata from the DB
222 */
223 function loadFromDB() {
224 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
225 $fname = 'Image::loadFromDB';
226 wfProfileIn( $fname );
227
228 $dbr =& wfGetDB( DB_SLAVE );
229 $row = $dbr->selectRow( 'image',
230 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
231 array( 'img_name' => $this->name ), $fname );
232 if ( $row ) {
233 $this->fromSharedDirectory = false;
234 $this->fileExists = true;
235 $this->loadFromRow( $row );
236 $this->imagePath = $this->getFullPath();
237 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
238 # In case we're on a wgCapitalLinks=false wiki, we
239 # capitalize the first letter of the filename before
240 # looking it up in the shared repository.
241 $name = $wgLang->ucfirst($this->name);
242
243 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
244 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
245 array( 'img_name' => $name ), $fname );
246 if ( $row ) {
247 $this->fromSharedDirectory = true;
248 $this->fileExists = true;
249 $this->imagePath = '';
250 $this->name = $name;
251 $this->loadFromRow( $row );
252 }
253 }
254
255 if ( !$row ) {
256 $this->size = 0;
257 $this->width = 0;
258 $this->height = 0;
259 $this->bits = 0;
260 $this->type = 0;
261 $this->fileExists = false;
262 $this->fromSharedDirectory = false;
263 }
264
265 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
266 $this->dataLoaded = true;
267 }
268
269 /*
270 * Load image metadata from a DB result row
271 */
272 function loadFromRow( &$row ) {
273 $this->size = $row->img_size;
274 $this->width = $row->img_width;
275 $this->height = $row->img_height;
276 $this->bits = $row->img_bits;
277 $this->type = $row->img_type;
278 $this->dataLoaded = true;
279 }
280
281 /**
282 * Load image metadata from cache or DB, unless already loaded
283 */
284 function load() {
285 if ( !$this->dataLoaded ) {
286 if ( !$this->loadFromCache() ) {
287 $this->loadFromDB();
288 if ( $this->fileExists ) {
289 $this->saveToCache();
290 }
291 }
292 $this->dataLoaded = true;
293 }
294 }
295
296 /**
297 * Return the name of this image
298 * @access public
299 */
300 function getName() {
301 return $this->name;
302 }
303
304 /**
305 * Return the associated title object
306 * @access public
307 */
308 function getTitle() {
309 return $this->title;
310 }
311
312 /**
313 * Return the URL of the image file
314 * @access public
315 */
316 function getURL() {
317 if ( !$this->url ) {
318 $this->load();
319 if($this->fileExists) {
320 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
321 } else {
322 $this->url = '';
323 }
324 }
325 return $this->url;
326 }
327
328 function getViewURL() {
329 if( $this->mustRender() ) {
330 return $this->createThumb( $this->getWidth() );
331 } else {
332 return $this->getURL();
333 }
334 }
335
336 /**
337 * Return the image path of the image in the
338 * local file system as an absolute path
339 * @access public
340 */
341 function getImagePath() {
342 $this->load();
343 return $this->imagePath;
344 }
345
346 /**
347 * Return the width of the image
348 *
349 * Returns -1 if the file specified is not a known image type
350 * @access public
351 */
352 function getWidth() {
353 $this->load();
354 return $this->width;
355 }
356
357 /**
358 * Return the height of the image
359 *
360 * Returns -1 if the file specified is not a known image type
361 * @access public
362 */
363 function getHeight() {
364 $this->load();
365 return $this->height;
366 }
367
368 /**
369 * Return the size of the image file, in bytes
370 * @access public
371 */
372 function getSize() {
373 $this->load();
374 return $this->size;
375 }
376
377 /**
378 * Return the type of the image
379 *
380 * - 1 GIF
381 * - 2 JPG
382 * - 3 PNG
383 * - 15 WBMP
384 * - 16 XBM
385 */
386 function getType() {
387 $this->load();
388 return $this->type;
389 }
390
391 /**
392 * Return the escapeLocalURL of this image
393 * @access public
394 */
395 function getEscapeLocalURL() {
396 $this->getTitle();
397 return $this->title->escapeLocalURL();
398 }
399
400 /**
401 * Return the escapeFullURL of this image
402 * @access public
403 */
404 function getEscapeFullURL() {
405 $this->getTitle();
406 return $this->title->escapeFullURL();
407 }
408
409 /**
410 * Return the URL of an image, provided its name.
411 *
412 * @param string $name Name of the image, without the leading "Image:"
413 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
414 * @access public
415 * @static
416 */
417 function imageUrl( $name, $fromSharedDirectory = false ) {
418 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
419 if($fromSharedDirectory) {
420 $base = '';
421 $path = $wgSharedUploadPath;
422 } else {
423 $base = $wgUploadBaseUrl;
424 $path = $wgUploadPath;
425 }
426 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
427 return wfUrlencode( $url );
428 }
429
430 /**
431 * Returns true if the image file exists on disk.
432 *
433 * @access public
434 */
435 function exists() {
436 $this->load();
437 return $this->fileExists;
438 }
439
440 /**
441 *
442 * @access private
443 */
444 function thumbUrl( $width, $subdir='thumb') {
445 global $wgUploadPath, $wgUploadBaseUrl,
446 $wgSharedUploadPath,$wgSharedUploadDirectory;
447 $name = $this->thumbName( $width );
448 if($this->fromSharedDirectory) {
449 $base = '';
450 $path = $wgSharedUploadPath;
451 } else {
452 $base = $wgUploadBaseUrl;
453 $path = $wgUploadPath;
454 }
455 $url = "{$base}{$path}/{$subdir}" .
456 wfGetHashPath($name, $this->fromSharedDirectory)
457 . "{$name}";
458 return wfUrlencode($url);
459 }
460
461 /**
462 * Return the file name of a thumbnail of the specified width
463 *
464 * @param integer $width Width of the thumbnail image
465 * @param boolean $shared Does the thumbnail come from the shared repository?
466 * @access private
467 */
468 function thumbName( $width, $shared=false ) {
469 $thumb = $width."px-".$this->name;
470 if( $this->extension == 'svg' ) {
471 # Rasterize SVG vector images to PNG
472 $thumb .= '.png';
473 }
474 return $thumb;
475 }
476
477 /**
478 * Create a thumbnail of the image having the specified width/height.
479 * The thumbnail will not be created if the width is larger than the
480 * image's width. Let the browser do the scaling in this case.
481 * The thumbnail is stored on disk and is only computed if the thumbnail
482 * file does not exist OR if it is older than the image.
483 * Returns the URL.
484 *
485 * Keeps aspect ratio of original image. If both width and height are
486 * specified, the generated image will be no bigger than width x height,
487 * and will also have correct aspect ratio.
488 *
489 * @param integer $width maximum width of the generated thumbnail
490 * @param integer $height maximum height of the image (optional)
491 * @access public
492 */
493 function createThumb( $width, $height=-1 ) {
494 $thumb = $this->getThumbnail( $width, $height );
495 if( is_null( $thumb ) ) return '';
496 return $thumb->getUrl();
497 }
498
499 /**
500 * As createThumb, but returns a ThumbnailImage object. This can
501 * provide access to the actual file, the real size of the thumb,
502 * and can produce a convenient <img> tag for you.
503 *
504 * @param integer $width maximum width of the generated thumbnail
505 * @param integer $height maximum height of the image (optional)
506 * @return ThumbnailImage
507 * @access public
508 */
509 function &getThumbnail( $width, $height=-1 ) {
510 if ( $height == -1 ) {
511 return $this->renderThumb( $width );
512 }
513 $this->load();
514 if ( $width < $this->width ) {
515 $thumbheight = $this->height * $width / $this->width;
516 $thumbwidth = $width;
517 } else {
518 $thumbheight = $this->height;
519 $thumbwidth = $this->width;
520 }
521 if ( $thumbheight > $height ) {
522 $thumbwidth = $thumbwidth * $height / $thumbheight;
523 $thumbheight = $height;
524 }
525 $thumb = $this->renderThumb( $thumbwidth );
526 if( is_null( $thumb ) ) {
527 $thumb = $this->iconThumb();
528 }
529 return $thumb;
530 }
531
532 /**
533 * @return ThumbnailImage
534 */
535 function iconThumb() {
536 global $wgStylePath, $wgStyleDirectory;
537
538 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
539 foreach( $try as $icon ) {
540 $path = '/common/images/' . $icon;
541 $filepath = $wgStyleDirectory . $path;
542 if( file_exists( $filepath ) ) {
543 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
544 }
545 }
546 return null;
547 }
548
549 /**
550 * Create a thumbnail of the image having the specified width.
551 * The thumbnail will not be created if the width is larger than the
552 * image's width. Let the browser do the scaling in this case.
553 * The thumbnail is stored on disk and is only computed if the thumbnail
554 * file does not exist OR if it is older than the image.
555 * Returns an object which can return the pathname, URL, and physical
556 * pixel size of the thumbnail -- or null on failure.
557 *
558 * @return ThumbnailImage
559 * @access private
560 */
561 function /* private */ renderThumb( $width, $useScript = true ) {
562 global $wgImageMagickConvertCommand;
563 global $wgUseImageMagick;
564 global $wgUseSquid, $wgInternalServer;
565 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
566
567 $width = IntVal( $width );
568
569 $this->load();
570 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
571 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).'/'.$thumbName;
572 $thumbUrl = $this->thumbUrl( $width );
573 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
574 if ( ! $this->exists() )
575 {
576 # If there is no image, there will be no thumbnail
577 return null;
578 }
579
580 # Sanity check $width
581 if( $width <= 0 ) {
582 # BZZZT
583 return null;
584 }
585
586 if( $width > $this->width && !$this->mustRender() ) {
587 # Don't make an image bigger than the source
588 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
589 }
590
591 $height = floor( $this->height * ( $width/$this->width ) );
592
593 // Generate thumb.php URL if possible
594 $thumbScript = false;
595 $scriptUrl = false;
596
597 if ( $this->fromSharedDirectory ) {
598 if ( $wgSharedThumbnailScriptPath ) {
599 $thumbScript = $wgSharedThumbnailScriptPath;
600 }
601 } else {
602 if ( $wgThumbnailScriptPath ) {
603 $thumbScript = $wgThumbnailScriptPath;
604 }
605 }
606 if ( $thumbScript ) {
607 $scriptUrl = $thumbScript . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
608 if ( $useScript ) {
609 // Use thumb.php to render the image
610 return new ThumbnailImage( $scriptUrl, $width, $height );
611 }
612 }
613
614 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
615 if( $this->extension == 'svg' ) {
616 global $wgSVGConverters, $wgSVGConverter;
617 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
618 global $wgSVGConverterPath;
619 $cmd = str_replace(
620 array( '$path/', '$width', '$input', '$output' ),
621 array( $wgSVGConverterPath,
622 $width,
623 escapeshellarg( $this->imagePath ),
624 escapeshellarg( $thumbPath ) ),
625 $wgSVGConverters[$wgSVGConverter] );
626 $conv = shell_exec( $cmd );
627 } else {
628 $conv = false;
629 }
630 } elseif ( $wgUseImageMagick ) {
631 # use ImageMagick
632 # Specify white background color, will be used for transparent images
633 # in Internet Explorer/Windows instead of default black.
634 $cmd = $wgImageMagickConvertCommand .
635 " -quality 85 -background white -geometry {$width} ".
636 escapeshellarg($this->imagePath) . " " .
637 escapeshellarg($thumbPath);
638 $conv = shell_exec( $cmd );
639 } else {
640 # Use PHP's builtin GD library functions.
641 #
642 # First find out what kind of file this is, and select the correct
643 # input routine for this.
644
645 $truecolor = false;
646
647 switch( $this->type ) {
648 case 1: # GIF
649 $src_image = imagecreatefromgif( $this->imagePath );
650 break;
651 case 2: # JPG
652 $src_image = imagecreatefromjpeg( $this->imagePath );
653 $truecolor = true;
654 break;
655 case 3: # PNG
656 $src_image = imagecreatefrompng( $this->imagePath );
657 $truecolor = ( $this->bits > 8 );
658 break;
659 case 15: # WBMP for WML
660 $src_image = imagecreatefromwbmp( $this->imagePath );
661 break;
662 case 16: # XBM
663 $src_image = imagecreatefromxbm( $this->imagePath );
664 break;
665 default:
666 return 'Image type not supported';
667 break;
668 }
669 if ( $truecolor ) {
670 $dst_image = imagecreatetruecolor( $width, $height );
671 } else {
672 $dst_image = imagecreate( $width, $height );
673 }
674 imagecopyresampled( $dst_image, $src_image,
675 0,0,0,0,
676 $width, $height, $this->width, $this->height );
677 switch( $this->type ) {
678 case 1: # GIF
679 case 3: # PNG
680 case 15: # WBMP
681 case 16: # XBM
682 #$thumbUrl .= ".png";
683 #$thumbPath .= ".png";
684 imagepng( $dst_image, $thumbPath );
685 break;
686 case 2: # JPEG
687 #$thumbUrl .= ".jpg";
688 #$thumbPath .= ".jpg";
689 imageinterlace( $dst_image );
690 imagejpeg( $dst_image, $thumbPath, 95 );
691 break;
692 default:
693 break;
694 }
695 imagedestroy( $dst_image );
696 imagedestroy( $src_image );
697 }
698 #
699 # Check for zero-sized thumbnails. Those can be generated when
700 # no disk space is available or some other error occurs
701 #
702 if( file_exists( $thumbPath ) ) {
703 $thumbstat = stat( $thumbPath );
704 if( $thumbstat['size'] == 0 ) {
705 unlink( $thumbPath );
706 }
707 }
708
709 # Purge squid
710 # This has to be done after the image is updated and present for all machines on NFS,
711 # or else the old version might be stored into the squid again
712 if ( $wgUseSquid ) {
713 $urlArr = Array(
714 $wgInternalServer.$thumbUrl
715 );
716 if ( $scriptUrl ) {
717 $urlArr[] = $scriptUrl;
718 }
719 wfPurgeSquidServers($urlArr);
720 }
721 }
722 return new ThumbnailImage( $thumbUrl, $width, $height );
723 } // END OF function createThumb
724
725 /**
726 * Return the image history of this image, line by line.
727 * starts with current version, then old versions.
728 * uses $this->historyLine to check which line to return:
729 * 0 return line for current version
730 * 1 query for old versions, return first one
731 * 2, ... return next old version from above query
732 *
733 * @access public
734 */
735 function nextHistoryLine() {
736 $fname = 'Image::nextHistoryLine()';
737 $dbr =& wfGetDB( DB_SLAVE );
738 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
739 $this->historyRes = $dbr->select( 'image',
740 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
741 array( 'img_name' => $this->title->getDBkey() ),
742 $fname
743 );
744 if ( 0 == wfNumRows( $this->historyRes ) ) {
745 return FALSE;
746 }
747 } else if ( $this->historyLine == 1 ) {
748 $this->historyRes = $dbr->select( 'oldimage',
749 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
750 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
751 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
752 );
753 }
754 $this->historyLine ++;
755
756 return $dbr->fetchObject( $this->historyRes );
757 }
758
759 /**
760 * Reset the history pointer to the first element of the history
761 * @access public
762 */
763 function resetHistory() {
764 $this->historyLine = 0;
765 }
766
767 /**
768 * Return true if the file is of a type that can't be directly
769 * rendered by typical browsers and needs to be re-rasterized.
770 * @return bool
771 */
772 function mustRender() {
773 $this->load();
774 return ( $this->extension == 'svg' );
775 }
776
777 /**
778 * Return the full filesystem path to the file. Note that this does
779 * not mean that a file actually exists under that location.
780 *
781 * This path depends on whether directory hashing is active or not,
782 * i.e. whether the images are all found in the same directory,
783 * or in hashed paths like /images/3/3c.
784 *
785 * @access public
786 * @param boolean $fromSharedDirectory Return the path to the file
787 * in a shared repository (see $wgUseSharedRepository and related
788 * options in DefaultSettings.php) instead of a local one.
789 *
790 */
791 function getFullPath( $fromSharedRepository = false ) {
792 global $wgUploadDirectory, $wgSharedUploadDirectory;
793 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
794
795 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
796 $wgUploadDirectory;
797 $name = $this->name;
798 $fullpath = $dir . wfGetHashPath($name, $fromSharedRepository) . $name;
799 return $fullpath;
800 }
801
802 /**
803 * @return bool
804 * @static
805 */
806 function isKnownImageExtension( $ext ) {
807 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
808 return in_array( $ext, $extensions );
809 }
810
811 /**
812 * Record an image upload in the upload log and the image table
813 */
814 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
815 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
816 global $wgUseCopyrightUpload;
817
818 $fname = 'Image::recordUpload';
819 $dbw =& wfGetDB( DB_MASTER );
820
821 # img_name must be unique
822 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
823 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
824 }
825
826 // Fill metadata fields by querying the file
827 $this->loadFromFile();
828 $this->saveToCache();
829
830 // Fail now if the image isn't there
831 if ( !$this->fileExists || $this->fromSharedDirectory ) {
832 return false;
833 }
834
835 if ( $wgUseCopyrightUpload ) {
836 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
837 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
838 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
839 } else {
840 $textdesc = $desc;
841 }
842
843 $now = wfTimestampNow();
844
845 # Test to see if the row exists using INSERT IGNORE
846 # This avoids race conditions by locking the row until the commit, and also
847 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
848 $dbw->insert( 'image',
849 array(
850 'img_name' => $this->name,
851 'img_size'=> $this->size,
852 'img_width' => $this->width,
853 'img_height' => $this->height,
854 'img_bits' => $this->bits,
855 'img_type' => $this->type,
856 'img_timestamp' => $dbw->timestamp($now),
857 'img_description' => $desc,
858 'img_user' => $wgUser->getID(),
859 'img_user_text' => $wgUser->getName(),
860 ), $fname, 'IGNORE'
861 );
862 $descTitle = $this->getTitle();
863
864 if ( $dbw->affectedRows() ) {
865 # Successfully inserted, this is a new image
866 $id = $descTitle->getArticleID();
867
868 if ( $id == 0 ) {
869 $article = new Article( $descTitle );
870 $article->insertNewArticle( $textdesc, $desc, false, false, true );
871 }
872 } else {
873 # Collision, this is an update of an image
874 # Insert previous contents into oldimage
875 $dbw->insertSelect( 'oldimage', 'image',
876 array(
877 'oi_name' => 'img_name',
878 'oi_archive_name' => $dbw->addQuotes( $oldver ),
879 'oi_size' => 'img_size',
880 'oi_width' => 'img_width',
881 'oi_height' => 'img_height',
882 'oi_bits' => 'img_bits',
883 'oi_type' => 'img_type',
884 'oi_timestamp' => 'img_timestamp',
885 'oi_description' => 'img_description',
886 'oi_user' => 'img_user',
887 'oi_user_text' => 'img_user_text',
888 ), array( 'img_name' => $this->name ), $fname
889 );
890
891 # Update the current image row
892 $dbw->update( 'image',
893 array( /* SET */
894 'img_size' => $this->size,
895 'img_width' => $this->width,
896 'img_height' => $this->height,
897 'img_bits' => $this->bits,
898 'img_type' => $this->type,
899 'img_timestamp' => $dbw->timestamp(),
900 'img_user' => $wgUser->getID(),
901 'img_user_text' => $wgUser->getName(),
902 'img_description' => $desc,
903 ), array( /* WHERE */
904 'img_name' => $this->name
905 ), $fname
906 );
907
908 # Invalidate the cache for the description page
909 $descTitle->invalidateCache();
910 }
911
912 $log = new LogPage( 'upload' );
913 $log->addEntry( 'upload', $descTitle, $desc );
914
915 return true;
916 }
917
918 } //class
919
920
921 /**
922 * Returns the image directory of an image
923 * If the directory does not exist, it is created.
924 * The result is an absolute path.
925 *
926 * This function is called from thumb.php before Setup.php is included
927 *
928 * @param string $fname file name of the image file
929 * @access public
930 */
931 function wfImageDir( $fname ) {
932 global $wgUploadDirectory, $wgHashedUploadDirectory;
933
934 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
935
936 $hash = md5( $fname );
937 $oldumask = umask(0);
938 $dest = $wgUploadDirectory . '/' . $hash{0};
939 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
940 $dest .= '/' . substr( $hash, 0, 2 );
941 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
942
943 umask( $oldumask );
944 return $dest;
945 }
946
947 /**
948 * Returns the image directory of an image's thubnail
949 * If the directory does not exist, it is created.
950 * The result is an absolute path.
951 *
952 * This function is called from thumb.php before Setup.php is included
953 *
954 * @param string $fname file name of the thumbnail file, including file size prefix
955 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
956 * @param boolean $shared (optional) use the shared upload directory
957 * @access public
958 */
959 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false) {
960 return wfImageArchiveDir( $fname, $subdir, $shared );
961 }
962
963 /**
964 * Returns the image directory of an image's old version
965 * If the directory does not exist, it is created.
966 * The result is an absolute path.
967 *
968 * This function is called from thumb.php before Setup.php is included
969 *
970 * @param string $fname file name of the thumbnail file, including file size prefix
971 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
972 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
973 * @access public
974 */
975 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
976 global $wgUploadDirectory, $wgHashedUploadDirectory,
977 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
978 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
979 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
980 if (!$hashdir) { return $dir.'/'.$subdir; }
981 $hash = md5( $fname );
982 $oldumask = umask(0);
983 # Suppress warning messages here; if the file itself can't
984 # be written we'll worry about it then.
985 $archive = $dir.'/'.$subdir;
986 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
987 $archive .= '/' . $hash{0};
988 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
989 $archive .= '/' . substr( $hash, 0, 2 );
990 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
991
992 umask( $oldumask );
993 return $archive;
994 }
995
996
997 /*
998 * Return the hash path component of an image path (URL or filesystem),
999 * e.g. "/3/3c/", or just "/" if hashing is not used.
1000 *
1001 * @param $dbkey The filesystem / database name of the file
1002 * @param $fromSharedDirectory Use the shared file repository? It may
1003 * use different hash settings from the local one.
1004 */
1005 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1006 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1007 global $wgHashedUploadDirectory;
1008
1009 $ishashed = $fromSharedDirectory ? $wgHashedSharedUploadDirectory :
1010 $wgHashedUploadDirectory;
1011 if($ishashed) {
1012 $hash = md5($dbkey);
1013 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1014 } else {
1015 return '/';
1016 }
1017 }
1018
1019 /**
1020 * Returns the image URL of an image's old version
1021 *
1022 * @param string $fname file name of the image file
1023 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1024 * @access public
1025 */
1026 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1027 global $wgUploadPath, $wgHashedUploadDirectory;
1028
1029 if ($wgHashedUploadDirectory) {
1030 $hash = md5( substr( $name, 15) );
1031 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1032 substr( $hash, 0, 2 ) . '/'.$name;
1033 } else {
1034 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1035 }
1036 return wfUrlencode($url);
1037 }
1038
1039 /**
1040 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1041 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1042 *
1043 * @param string $length
1044 * @return int Length in pixels
1045 */
1046 function wfScaleSVGUnit( $length ) {
1047 static $unitLength = array(
1048 'px' => 1.0,
1049 'pt' => 1.25,
1050 'pc' => 15.0,
1051 'mm' => 3.543307,
1052 'cm' => 35.43307,
1053 'in' => 90.0,
1054 '' => 1.0, // "User units" pixels by default
1055 '%' => 2.0, // Fake it!
1056 );
1057 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1058 $length = FloatVal( $matches[1] );
1059 $unit = $matches[2];
1060 return round( $length * $unitLength[$unit] );
1061 } else {
1062 // Assume pixels
1063 return round( FloatVal( $length ) );
1064 }
1065 }
1066
1067 /**
1068 * Compatible with PHP getimagesize()
1069 * @todo support gzipped SVGZ
1070 * @todo check XML more carefully
1071 * @todo sensible defaults
1072 *
1073 * @param string $filename
1074 * @return array
1075 */
1076 function wfGetSVGsize( $filename ) {
1077 $width = 256;
1078 $height = 256;
1079
1080 // Read a chunk of the file
1081 $f = fopen( $filename, "rt" );
1082 if( !$f ) return false;
1083 $chunk = fread( $f, 4096 );
1084 fclose( $f );
1085
1086 // Uber-crappy hack! Run through a real XML parser.
1087 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1088 return false;
1089 }
1090 $tag = $matches[1];
1091 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1092 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1093 }
1094 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1095 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1096 }
1097
1098 return array( $width, $height, 'SVG',
1099 "width=\"$width\" height=\"$height\"" );
1100 }
1101
1102 /**
1103 * Is an image on the bad image list?
1104 */
1105 function wfIsBadImage( $name ) {
1106 global $wgLang;
1107
1108 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1109 foreach ( $lines as $line ) {
1110 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE ) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1111 $t = Title::newFromText( $m[1] );
1112 if ( $t->getDBkey() == $name ) {
1113 return true;
1114 }
1115 }
1116 }
1117 return false;
1118 }
1119
1120
1121
1122 /**
1123 * Wrapper class for thumbnail images
1124 * @package MediaWiki
1125 */
1126 class ThumbnailImage {
1127 /**
1128 * @param string $path Filesystem path to the thumb
1129 * @param string $url URL path to the thumb
1130 * @access private
1131 */
1132 function ThumbnailImage( $url, $width, $height ) {
1133 $this->url = $url;
1134 $this->width = $width;
1135 $this->height = $height;
1136 }
1137
1138 /**
1139 * @return string The thumbnail URL
1140 */
1141 function getUrl() {
1142 return $this->url;
1143 }
1144
1145 /**
1146 * Return HTML <img ... /> tag for the thumbnail, will include
1147 * width and height attributes and a blank alt text (as required).
1148 *
1149 * You can set or override additional attributes by passing an
1150 * associative array of name => data pairs. The data will be escaped
1151 * for HTML output, so should be in plaintext.
1152 *
1153 * @param array $attribs
1154 * @return string
1155 * @access public
1156 */
1157 function toHtml( $attribs = array() ) {
1158 $attribs['src'] = $this->url;
1159 $attribs['width'] = $this->width;
1160 $attribs['height'] = $this->height;
1161 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1162
1163 $html = '<img ';
1164 foreach( $attribs as $name => $data ) {
1165 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1166 }
1167 $html .= '/>';
1168 return $html;
1169 }
1170
1171 }
1172 ?>